package cool.taomu.toolkit.utils

import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.google.common.util.concurrent.UncheckedExecutionException
import java.math.BigInteger
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit

class StringUtils {
    val static Cache<String, String> STRING_160BIT_CACHE = CacheBuilder.newBuilder.maximumSize(1000) // 最多缓存 1000 个条目
    .expireAfterWrite(10, TimeUnit.MINUTES) // 写入后 10 分钟过期
    .build;

    def static String stringTo160Bit(String arg) {
        try {
            return STRING_160BIT_CACHE.get(arg)[compute160BitHash(arg)];
        } catch (ExecutionException | UncheckedExecutionException e) {
            // 处理异常（理论上不会发生）
            throw new RuntimeException("Error computing 160-bit hash for: " + arg, e.getCause());
        }
    }

    def static compute160BitHash(String input) {
        var MessageDigest digest = MessageDigest.getInstance("SHA-1");
        var byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
        return new BigInteger(1, hash).toString(2); // 二进制表示;
    }
}
